/**
 * @ProjectName:Backend
 * @Title: UploadFile
 * @Package com.phrp.util.oss
 * @Description: 上传文件
 * @author SuShuChao
 * @date 2024/4/22 20:52
 * @version V1.0
 * Copyright (c) 2024, 2034279227@qq.com All Rights Reserved.
 */
package com.phrp.util.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.phrp.exception.CustomizationException;
import com.phrp.util.DateTimeUtil;
import com.phrp.util.returnResult.ReturnInfoEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

@Component
public class UploadFile {
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.dir.prefix.img}")
    private String dirPrefixImg;

    @Value("${aliyun.oss.dir.prefix.file}")
    private String dirPrefixFile;

    @Resource
    private OSSClient ossClient;

    /**
     * 上传图片工具类
     * @param fileType（文件类型）
     * @param file（文件）
     * @return
     */
    public String uploadImg(String[] fileType,MultipartFile file){
        // 判空
        if(file.isEmpty()){
            return "false";
        }
        boolean bol = assessFileType(fileType,file);
        if (!bol) {
            return "false";
        }
        String url = "";

        try {
            InputStream inputStream = file.getInputStream();
            //整理文件名称
            String fileName = getImgName(file);
            //创建PutObject请求
            PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream);
            System.out.println(result);

            //返回完整路径给前端
            url = "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + fileName;
        } catch (IOException e) {
            throw new CustomizationException(ReturnInfoEnum.UPLOAD_FAIL);
        }
        return url;
    }

    /**
     * 上传文件工具类
     * @param fileType（文件类型）
     * @param file（文件）
     * @return
     */
    public String uploadFile(String[] fileType,MultipartFile file){
        // 判空
        if(file.isEmpty()){
            return "false";
        }
        boolean bol = assessFileType(fileType,file);
        if (!bol) {
            return "false";
        }
        String url = "";

        try {
            InputStream inputStream = file.getInputStream();
            //整理文件名称
            String fileName = getFileName(file);
            //创建PutObject请求
            PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream);
            System.out.println(result);

            //返回完整路径给前端
            url = "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + fileName;
        } catch (IOException e) {
            throw new CustomizationException(ReturnInfoEnum.UPLOAD_FAIL);
        }
        return url;
    }

    /**
     * 整理上传 图片 和 路径
     * @param file
     * @return
     */
    private String getImgName(MultipartFile file) {
        // 文件后缀
        String suffixName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //文件名称
        String fileName = UUID.randomUUID().toString() + suffixName;

        //当前年月日
        String loalYmd = DateTimeUtil.localYmd();
        String path = dirPrefixImg + loalYmd + "/" + fileName;

        return path;
    }

    /**
     * 整理上传 文件名称 和 路径
     * @param file
     * @return
     */
    private String getFileName(MultipartFile file) {
        // 文件后缀
        String suffixName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //文件名称
        String fileName = UUID.randomUUID().toString() + suffixName;

        //当前年月日
        String loalYmd = DateTimeUtil.localYmd();
        String path = dirPrefixFile + loalYmd + "/" + fileName;

        return path;
    }

    /**
     * 判断文件格式
     */
    private boolean assessFileType(String[] fileType,MultipartFile file) {
        //对图片的后缀名做校验
        boolean isPass = false;
        for (String type : fileType) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isPass = true;
                break;
            }
        }
        return isPass;
    }

}
